<?php


namespace UU\Suite\Kernel\Traits;


use GuzzleHttp\Client;
use UU\Suite\Kernel\Contracts\HttpClientInterface;
use UU\Suite\Kernel\HttpClient;

trait InteractWithHttpClient
{
    protected ?HttpClientInterface $httpClient = null;

    public function getHttpClient(): HttpClientInterface
    {
        if (!$this->httpClient) {
            $this->httpClient = $this->createHttpClient($this->getHttpClientDefaultOptions());
        }

        return $this->httpClient;
    }

    public function setHttpClient(HttpClientInterface $httpClient): self
    {
        $this->httpClient = $httpClient;

        return $this;
    }

    protected function createHttpClient($config = []): HttpClientInterface
    {
        $scopedHttpClientClass = \sprintf('%s\HttpClient', (new \ReflectionClass($this))->getNamespaceName());
        $defaultOptions = $this->getHttpClientDefaultOptions();
        if (\class_exists($scopedHttpClientClass)) {
            return (new $scopedHttpClientClass(array_merge($defaultOptions,$config)));
        }
        return (new HttpClient(new Client(array_merge($defaultOptions,$config))));
    }

    protected function getHttpClientDefaultOptions(): array
    {
        return [];
    }
}